package org.jeecg.modules.solitaire_app.app.controller;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.solitaire_app.app.entity.*;
import org.jeecg.modules.solitaire_app.app.service.IYsyInquiryNoticeService;
import org.jeecg.modules.solitaire_app.app.service.IYsyInquiryService;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.solitaire_app.app.service.IYsySystemContentService;
import org.jeecg.modules.solitaire_app.app.service.IYsyUsersService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 询价
 * @Author: jeecg-boot
 * @Date: 2024-01-24
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "询价")
@RestController
@RequestMapping("/app/ysyInquiry")
public class YsyInquiryController extends JeecgController<YsyInquiry, IYsyInquiryService> {
    @Autowired
    private IYsyInquiryService ysyInquiryService;
    @Autowired
    private IYsyUsersService ysyUsersService;
    @Value("${tengcent.apiMap}")
    private String apiMap;
    @Autowired
    private IYsySystemContentService ysySystemContentService;
    @Autowired
    private IYsyInquiryNoticeService ysyInquiryNoticeService;

    /**
     * 分页列表查询
     *
     * @param ysyInquiry
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "询价-分页列表查询")
    @ApiOperation(value = "询价-分页列表查询", notes = "询价-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(YsyInquiry ysyInquiry,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<YsyInquiry> queryWrapper = QueryGenerator.initQueryWrapper(ysyInquiry, req.getParameterMap());
        Page<YsyInquiry> page = new Page<YsyInquiry>(pageNo, pageSize);
        IPage<YsyInquiry> pageList = ysyInquiryService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param ysyInquiry
     * @return
     */
    @AutoLog(value = "询价-添加")
    @ApiOperation(value = "询价-添加", notes = "询价-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody YsyInquiry ysyInquiry) {

        YsyUsers ysyUsers = ysyUsersService.getOne(Wrappers.<YsyUsers>lambdaQuery()
                .eq(YsyUsers::getId, ysyInquiry.getUserId()).eq(YsyUsers::getSource, 1));
        if (ObjectUtil.isEmpty(ysyUsers)) {
            return Result.error("未找到该用户");
        }
        ysyInquiry.setUserName(ObjectUtil.isNotEmpty(ysyUsers.getRealName()) ? ysyUsers.getRealName() : ysyUsers.getNickName());
        ysyInquiry.setUserPhone(ysyUsers.getPhone());

        if (ObjectUtil.isEmpty(ysyInquiry.getZhdLat()) && ObjectUtil.isEmpty(ysyInquiry.getZhdLng())) {
            JSONObject jsonObject = getAddress(ysyInquiry.getZhdAddress());
            if (ObjectUtil.isEmpty(jsonObject)) {
                return Result.error("未找到该装货地！！！");
            }
            ysyInquiry.setZhdLat(jsonObject.getJSONObject("location").getString("lat"));
            ysyInquiry.setZhdLng(jsonObject.getJSONObject("location").getString("lng"));
        }

        if (ObjectUtil.isEmpty(ysyInquiry.getXhdLat()) && ObjectUtil.isEmpty(ysyInquiry.getZhdLng())) {
            JSONObject jsonObject = getAddress(ysyInquiry.getZhdAddress());
            if (ObjectUtil.isEmpty(jsonObject)) {
                return Result.error("未找到该卸货地！！！");
            }
            ysyInquiry.setXhdLat(jsonObject.getJSONObject("location").getString("lat"));
            ysyInquiry.setXhdLng(jsonObject.getJSONObject("location").getString("lng"));
        }

        String url = "https://apis.map.qq.com/ws/direction/v1/driving/?from="
                + (ysyInquiry.getZhdLat() + "," + ysyInquiry.getZhdLng())
                + "&to=" + (ysyInquiry.getXhdLat() + "," + ysyInquiry.getXhdLng())
                + "&key=" + this.apiMap;
        String jsonStr = HttpUtil.get(url);
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        if (jsonObject.getInteger("status") == 0) {

            BigDecimal minPrice = BigDecimal.ZERO;
            BigDecimal maxPrice = BigDecimal.ZERO;
            BigDecimal fdPrice = BigDecimal.valueOf(20);
            BigDecimal fdBfb = BigDecimal.valueOf(30);

            /*浮动价格*/
            YsySystemContent ysySystemContent = ysySystemContentService.getOne(Wrappers.<YsySystemContent>lambdaQuery()
                    .eq(YsySystemContent::getType, 13));
            if (ObjectUtil.isNotEmpty(ysySystemContent)) {
                fdPrice = BigDecimal.valueOf(Long.parseLong(ysySystemContent.getContent()));
            }

            /*浮动百分比*/
            YsySystemContent fdContent = ysySystemContentService.getOne(Wrappers.<YsySystemContent>lambdaQuery()
                    .eq(YsySystemContent::getType, 14));
            if (ObjectUtil.isNotEmpty(fdContent)) {
                fdBfb = BigDecimal.valueOf(Long.parseLong(fdContent.getContent()));
            }

            JSONObject resultObj = jsonObject.getJSONObject("result").getJSONArray("routes").getJSONObject(0);
            BigDecimal distance = resultObj.getBigDecimal("distance").divide(BigDecimal.valueOf(1000), 2, BigDecimal.ROUND_HALF_UP);
            BigDecimal priceDec = distance.multiply(fdBfb).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_UP);

            if (priceDec.compareTo(minPrice) <= 0) {
                minPrice = fdPrice;
                maxPrice = minPrice.add(fdPrice);
            } else {
                minPrice = priceDec.subtract(fdPrice);
                maxPrice = priceDec.add(fdPrice);
            }

            String price = minPrice + "-" + maxPrice;
            ysyInquiry.setPrice(price);
            ysyInquiry.setDistance(distance);
        } else {
            return Result.error("轨迹不正确！！！");
        }

        ysyInquiryService.save(ysyInquiry);
        return Result.ok(ysyInquiry.getId());
    }

    public JSONObject getAddress(String addressName) {
        String url = "https://apis.map.qq.com/ws/geocoder/v1/?address=" + addressName + "&key=VBMBZ-5P4RW-QMURT-YAZXR-BVRE7-VHBN7";
        String jsonStr = HttpUtil.get(url);
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        if (jsonObject.getInteger("status") == 0) {
            JSONObject json = jsonObject.getJSONObject("result");
            return json;
        } else {
            return null;
        }
    }

    /**
     * 编辑
     *
     * @param ysyInquiry
     * @return
     */
    @AutoLog(value = "询价-编辑")
    @ApiOperation(value = "询价-编辑", notes = "询价-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody YsyInquiry ysyInquiry) {
        ysyInquiryService.updateById(ysyInquiry);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "询价-通过id删除")
    @ApiOperation(value = "询价-通过id删除", notes = "询价-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        ysyInquiryService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "询价-批量删除")
    @ApiOperation(value = "询价-批量删除", notes = "询价-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.ysyInquiryService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "询价-通过id查询")
    @ApiOperation(value = "询价-通过id查询", notes = "询价-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        YsyInquiry ysyInquiry = ysyInquiryService.getById(id);
        String cityName = extractCityName(ysyInquiry.getXhdAddress());
        List<YsyInquiryNotice> ysyInquiryNotices = ysyInquiryNoticeService.list(Wrappers.<YsyInquiryNotice>lambdaQuery()
                .like(YsyInquiryNotice::getZhdName,ysyInquiry.getZhdName())
                .like(YsyInquiryNotice::getXhdAddress,cityName));
        ysyInquiryNotices.stream().forEach(item->{
            item.setUserName(getReplace(3, 6, item.getUserName()));
            if (item.getPrice().length() >=4){
                item.setPrice(getReplace(1, 2, item.getPrice()));
            }else{
                item.setPrice(getReplace(1, 1, item.getPrice()));
            }
            item.setDistance(getReplace(1,1,item.getDistance()));
        });
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("ysyInquiryNotices",ysyInquiryNotices);
        jsonObject.put("ysyInquiry",ysyInquiry);
        return Result.ok(jsonObject);
    }

    public String getReplace(int startIndex, int endIndex, String val) {

        // 构建新的字符串，将指定范围内的内容替换为*
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < val.length(); i++) {
            if (i >= startIndex && i <= endIndex) {
                sb.append("*");
            } else {
                sb.append(val.charAt(i));
            }
        }
        return sb.toString();
    }


    private static String extractCityName(String input) {
        if (input.indexOf("新疆维吾尔自治区")!=-1){
            return "新疆";
        }
        if (input.indexOf("西藏自治区")!=-1){
            return "西藏";
        }
        if (input.indexOf("内蒙古自治区")!=-1){
            return "内蒙古";
        }
        if (input.indexOf("宁夏回族自治区")!=-1){
            return "宁夏";
        }
        if (input.indexOf("广西壮族自治区")!=-1){
            return "广西";
        }
        // 定义匹配模式，使用非贪婪匹配
        String pattern = "省(.*?市)";
        Pattern r = Pattern.compile(pattern);

        // 创建Matcher对象
        Matcher matcher = r.matcher(input);

        // 查找匹配
        if (matcher.find()) {
            // group(1)是第一个捕获组的内容
            return matcher.group(1);
        } else {
            return "";
        }
    }

    /**
     * 导出excel
     *
     * @param request
     * @param ysyInquiry
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, YsyInquiry ysyInquiry) {
        return super.exportXls(request, ysyInquiry, YsyInquiry.class, "询价");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, YsyInquiry.class);
    }

}
